package com.liuzhongni.wahahanews.fragment.newcolumnfragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.liuzhongni.wahahanews.R;
import com.liuzhongni.wahahanews.RefreshListView;
import com.liuzhongni.wahahanews.activity.DetailsActivity;
import com.liuzhongni.wahahanews.activity.MainActivity;
import com.liuzhongni.wahahanews.activity.NewsHeadlineDetailsActivity;
import com.liuzhongni.wahahanews.activity.SpacialActivity;
import com.liuzhongni.wahahanews.adapter.ListViewAdapterOfHeadline;
import com.liuzhongni.wahahanews.adapter.ViewPagerAdapterOfNewHeadline;
import com.liuzhongni.wahahanews.dao.Person;
import com.liuzhongni.wahahanews.game.Saizi;
import com.liuzhongni.wahahanews.headlineclass.ResponseEty;
import com.liuzhongni.wahahanews.headlineclass.ResponseEtySecond;
import com.liuzhongni.wahahanews.singleton.VolleySingleton;

import java.util.ArrayList;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;


/**
 * Created by admin on 2016/1/8.
 */
public class HeadLineFragment extends Fragment implements RefreshListView.OnRefreshListener, View.OnClickListener {
    private ListViewAdapterOfHeadline listViewAdapter;
    private RefreshListView listView;
    private ResponseEty ety = new ResponseEty();
    private String responceMore;
    private ResponseEty etyMore = new ResponseEty();
    private ArrayList<ResponseEtySecond> data;
    private int number = 20;
    private ImageView imageViewToTop;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_column_headline, null);
        imageViewToTop = (ImageView) view.findViewById(R.id.new_column_headline_iv);
        listView = (RefreshListView) view.findViewById(R.id.new_column_headline_lv);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork()
                .penaltyLog()
                .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects()
                .detectLeakedClosableObjects()
                .penaltyLog()
                .penaltyDeath()
                .build());
        //解析json方法
        headlineJson();
        listViewItemClick();
        imageViewToTop.setOnClickListener(this);
        return view;
    }

    //解析json
    public void headlineJson() {
        String url = "http://c.3g.163.com/nc/article/headline/T1348647909107/0-20.html";
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d("HeadLineFragment", response);
//                MainActivity.daoSession.getPersonDao().insert(new Person(20l,response,10));
                responceMore = response;
                Gson gson = new Gson();
                ety = gson.fromJson(response, ResponseEty.class);
                init();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(), "没成功", Toast.LENGTH_SHORT).show();
            }
        });
        VolleySingleton.getOurInstance().addRequest(request);
    }

    private void init() {
        listViewAdapter = new ListViewAdapterOfHeadline(getActivity(), ety);
        listView.setAdapter(listViewAdapter);
        listView.setOnRefreshListener(this);

    }

    private void listViewItemClick() {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (ety.getT1348647909107().get(position-1).getSkipType() != null) {
                    if (ety.getT1348647909107().get(position-1).getSkipType().equals("special")) {
                        Intent intent = new Intent(getActivity(), SpacialActivity.class);
                        intent.putExtra("skipType", ety.getT1348647909107().get(position-1).getSkipType());
                        intent.putExtra("specialID", ety.getT1348647909107().get(position-1).getSpecialID());
                        startActivity(intent);
                        return;
                    } else if (ety.getT1348647909107().get(position-1).getImgextra() != null) {
                        int num = ety.getT1348647909107().get(position-1).getSkipID().length();
                        String url = ety.getT1348647909107().get(position-1).getSkipID().replace("|", "/").substring(4, num);
                        Intent intent = new Intent(getActivity(), NewsHeadlineDetailsActivity.class);
                        intent.putExtra("url", url);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(getActivity(), DetailsActivity.class);
                        intent.putExtra("docid", ety.getT1348647909107().get(position-1).getDocid());
                        startActivity(intent);
                    }
                } else {
                    Intent intent = new Intent(getActivity(), DetailsActivity.class);
                    intent.putExtra("docid", ety.getT1348647909107().get(position-1).getDocid());
                    Log.d("HeadLineFragment", ety.getT1348647909107().get(position-1).getDocid());
                    startActivity(intent);
                    return;
                }
            }
        });
    }


    @Override
    public void onDownPullRefresh() {
        headlineJson();
        Log.d("HeadLineFragment", responceMore);
        listView.hideHeaderView();
        number = 20;
    }

    @Override
    public void onLoadingMore() {
        SystemClock.sleep(500);

        String url = "http://c.3g.163.com/nc/article/headline/T1348647909107/"+number+"-20.html";
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                etyMore = gson.fromJson(response, ResponseEty.class);
                data = etyMore.getT1348647909107();
                Log.d("HeadLineFragment", "data.size():" + data.size());
                data.remove(0);
                Log.d("HeadLineFragment", "data.size():" + data.size());
                listViewAdapter.addItem(data);

            }
        }, null);
        VolleySingleton.getOurInstance().getQueue().add(request);
        Log.d("HeadLineFragment", responceMore);

        listView.hideFooterView();
        number = number+20;
    }


//    @Override
//    public void onClick(View v) {
//        Toast.makeText(getActivity(), "wahhaa", Toast.LENGTH_SHORT).show();
//    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d("NewsFragment", "pause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d("NewsFragment", "stop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d("NewsFragment", "destroyview");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("NewsFragment", "destroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d("NewsFragment", "detach");
    }

    @Override
    public void onClick(View v) {
        Intent intent  = new Intent(getActivity(), Saizi.class);
        startActivity(intent);
//        listView.setSelection(0);
//        showShare();

    }
    private void showShare() {
        ShareSDK.initSDK(getActivity());
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(getString(R.string.ssdk_oks_share));
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

// 启动分享GUI
        oks.show(getActivity());
    }

    //                Log.d("HeadLineFragment", response);
//                Log.d("HeadLineFragment", "response.length():" + response.length());
//                response = response.substring(response.indexOf("\"ptime\""), response.length());
//                Log.d("HeadLineFragment", "response.length():" + response.length());
//
//                response = response.substring(response.indexOf(","), response.length());
//                Log.d("HeadLineFragment", "response.length():" + response.length());
//
//                Log.d("HeadLineFragment", response);

}
